import os.path
import time
import requests
import json


def get_html(search, page):
    page = int(page)
    n = 0
    list_img = []
    url = f'https://image.baidu.com/search/index?'
    hearders = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                      'Chrome/97.0.4692.99 Safari/537.36',
        'Referer': 'https://image.baidu.com/search/index?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&sf=1&fmq'
                   '=&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&fm=index&pos'
                   '=history&word=f1',
        'Cookie': 'BDqhfp=%E8%B5%9B%E8%BD%A6%26%2600-10-1undefined%26%260%26%261; '
                  'BIDUPSID=4C871D08D87F3527F2BA602CCD15A62F; PSTM=1643172923; '
                  'BAIDUID=4C871D08D87F3527CB12D7652033DE78:FG=1; BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; '
                  '__yjs_duid=1_cfa8bdb757648c24f9f195c721d8163b1643175027221; '
                  'H_PS_PSSID=35106_34584_35491_35796_35325_26350_35752_35746; firstShowTip=1; '
                  'indexPageSugList=%5B%22%E8%B5%9B%E8%BD%A6%22%5D; cleanHistoryStatus=0; '
                  'BAIDUID_BFESS=D2F860E053691100206B750233F2FFC1:FG=1; delPer=0; PSINO=5; '
                  'BA_HECTOR=05ak258ga121258lbk1gvd45u0q; BDRCVFR[dG2JNJb_ajR]=mk3SLVN4HKm; userFrom=null; '
                  'ariaDefaultTheme=undefined; '
                  'ab_sr=1.0'
                  '.1_YjJjNGJhODRhNmRlNjliNmRmZmVmMGU2ZDRlZjY0MDIxZmVhZTQ3MDc2MGMzMGM5MDhlZDUzNjU0OTc5N2VkYzdlM2MzMDA5MmM5ODI4NzczYWY4ZWYzNDE4ZmM2MTFj; BDRCVFR[-pGxjrCMryR]=mk3SLVN4HKm '
    }
    # 百度30为一页
    # 因为百度图片是以json来传递图片信息 所以需要传递params参数
    for i in range(0, page * 30, 30):
        pn = i
        params = {
            'tn': 'resultjson_com',
            'logid': '',
            'ipn': 'rj',
            'ct': '201326592',
            'is': '',
            'fp': 'result',
            'fr': '',
            # 这两个参数负责搜索
            'word': search,
            'queryWord': search,
            'cl': '2',
            'lm': '-1',
            'ie': 'utf - 8',
            'oe': 'utf - 8',
            'adpicid': '',
            'st': '-1',
            'z': '0',
            'ic': '0',
            'hd': '0',
            'latest': '0',
            'copyright': '0',
            's': '',
            'se': '',
            'tab': '',
            'width': '',
            'height': '',
            'face': '0',
            'istype': '2',
            'qc': '',
            'nc': '1',
            'expermode': '',
            'nojc': '',
            'isAsync': '',
            # pn ：以x为起始位
            'pn': pn,
            # rn：每页展示多少图片
            'rn': i * 30,
            'gsm': '',
            '1643544561760': '',
        }

        img_html = requests.get(url=url, headers=hearders, params=params)
        data = json.loads(img_html.text)['data']
        for j in data:
            try:
                imgUrl = j['hoverURL']
                # 数据清洗，防止在以title作为图片名时发生下载错误
                title = j['fromPageTitleEnc'].replace('?', '').replace('|', '').replace("\'", '').replace("\"", '').replace("——", '').replace(":", '').replace("—", '')
                n += 1
                print(title, imgUrl, f'第{n}张图片')
                with open(f'./resource/{title}.jpg', 'wb') as f:
                    f.write(requests.get(url=imgUrl, headers=hearders).content)
                time.sleep(1)
            except:
                print('图片错误')
    return list_img


def judge(input, typei):
    if typei == 1:
        if not input.isdigit():
            return True
        else:
            print('输入错误，应输入文字')
            return False
    elif typei == 2:
        if input.isdigit():
            return True
        else:
            print('输入错误，应输入数字')
            return False


user_input_search = input('请输入想要搜索的关键词： ')
user_input_int = input('请输入想搜索几页： ')

if not os.path.exists('resource'):
    os.makedirs('resource')

if judge(user_input_search, 1) and judge(user_input_int, 2):
        html = get_html(user_input_search, user_input_int)
        print(html)

